
(function() {
  // const http = require('http');
  // const url = require('url');
  const fs = require('fs');
  const axios = require('axios');
  const cheerio = require('cheerio');
  const iconv = require('iconv-lite');
  const util = require('util');

  axios({
    methods: 'get',
    url:
      'https://list.tmall.com/search_product.htm?spm=a221t.1476805.cat.19.52006769d615Pr&cat=54290107&q=%E4%BC%91%E9%97%B2%E5%A5%97%E8%A3%85',
    headers: {
      'content-type': 'text/html;charset=GBK'
    }
  })
    .then(res => {
      if (!res.data) {
        console.log('数据为空，无法追加');
        return false;
      }
      const contentBinary = iconv.decode(
        Buffer.from(util.inspect(res.data), 'binary'),
        'GBK'
      );

      const $ = cheerio.load(contentBinary, {
        normalizeWhitespace: true,
        decodeEntities: false
      });
      console.log($('.productTitle a').attr('title'));
      console.log($('em').attr('title'));
      fs.appendFile(
        './spider/taobao.txt',
        $('.productTitle a').attr('title'),
        'utf8',
        err => {
          if (err) throw err;
          console.log('数据已被追加到文件');
        }
      );
    })
    .catch(err => {
      if (err) throw err;
    });
})();
